import { PrismaClient } from "@prisma/client";
import { NextRequest, NextResponse } from "next/server";

interface TopicRequest {
  userId: string;
  avatar: string;
  content: string;
  images: string[];
  options: string[];
}

const prisma = new PrismaClient();
export async function DELETE(request: NextRequest) {
  try {
    // 解析请求中的id
    const url = request.nextUrl;
    const id = url.searchParams.get('id') as string ;

    // 首先，查找与这个id关联的用户
    const topic = await prisma.topic.findUnique({
      where: {
        id,
      },
    });

    // 如果用户不存在，返回错误
    if (!topic) {
      return NextResponse.json({ message: "topic not found" }, { status: 404 });
    }



    // 删除与这些topicId关联的所有Option
    await prisma.option.deleteMany({
      where: {
        topicId: id
      },
    });

    // 删除这些Topic
    await prisma.topic.deleteMany({
      where: {
        id
      },
    });


    // 返回成功响应
    return NextResponse.json({ message: "User and all related topics and options deleted successfully" }, { status: 200 });
  } catch (error) {
    // 处理可能出现的错误
    console.error("Error deleting user and related data:" + error);

    // 对于其他错误，返回内部错误消息
    return NextResponse.json({ message: "Internal error" }, { status: 500 });
  } finally {
    // 确保在请求结束后关闭PrismaClient
    prisma.$disconnect();
  }
}
export async function GET() {
  try {
    const topics = await prisma.topic.findMany({
      include: {
        options: true,
      },
    });
    return NextResponse.json(
      {
        topics,
      },
      { status: 200 }
    );
  } catch (e) {
    console.error("🚀 ~ file: route.ts:18 ~ GET ~ e:", e);
    return NextResponse.json(
      {
        message: "Internal Error",
      },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const data = (await request.json()) as TopicRequest;

    const topic = await prisma.topic.create({
      data: {
        userId: data.userId,
        avatar: data.avatar,
        content: data.content,
        images: data.images,
        options: {
          create: data.options.map((item) => ({
            key: item,
            value: 0,
          })),
        },
      },
      include: {
        options: true,
      },
    });
    return NextResponse.json(topic, { status: 200 });
  } catch (e) {
    console.error("🚀 ~ file: route.ts:16 ~ POST ~ e:", e);
    return NextResponse.json(
      {
        message: "Internal error",
      },
      { status: 500 }
    );
  }
}
